import asyncio
from typing import Dict, List, Tuple, Optional
from message_types import *
from texas_holdem import TexasHoldem, Player
from utils import serialize_card, serialize_player, log_game_event


class GameRoom:
    def __init__(self):
        self.room_state = RoomState.WAITING_FOR_PLAYERS
        self.game_state: Optional[GameState] = None
        self.betting_state: Optional[BettingState] = None

        # 房间配置
        self.total_players = 6
        self.ai_players = 5
        self.human_players: List[str] = []  # 真人玩家ID列表

        # 游戏引擎
        self.texas_holdem = TexasHoldem()
        self.current_round_name = "翻牌前"

        # 当前玩家状态
        self.current_player_index = 0
        self.players_acted = set()
        self.waiting_for_player = None  # 当前等待行动的玩家
        self.action_timeout_task = None

        # WebSocket回调（由websocket_handler设置）
        self.websocket_handler = None

        print("游戏房间已创建")

    async def add_player(self, player_name: str, total_players: int, ai_players: int) -> Tuple[bool, str]:
        """添加玩家到房间"""
        if self.room_state != RoomState.WAITING_FOR_PLAYERS:
            return False, "房间已开始游戏或已满"

        if player_name in self.human_players:
            return False, "玩家名已存在"

        # 更新房间配置（第一个玩家设置）
        if len(self.human_players) == 0:
            self.total_players = total_players
            self.ai_players = ai_players

            if ai_players >= total_players:
                return False, "AI玩家数量不能大于等于总玩家数"

        # 检查房间是否已满
        max_human_players = self.total_players - self.ai_players
        if len(self.human_players) >= max_human_players:
            return False, f"房间已满（最多{max_human_players}个真人玩家）"

        # 添加玩家
        self.human_players.append(player_name)

        # 重新配置texas_holdem的玩家
        await self._setup_players()

        print(f"玩家 {player_name} 加入房间 ({len(self.human_players)}/{max_human_players})")

        # 检查是否可以开始游戏
        if len(self.human_players) == max_human_players:
            self.room_state = RoomState.READY_TO_START
            print("房间已满，可以开始游戏")

        return True, "成功加入房间"

    async def _setup_players(self):
        """设置texas_holdem的玩家配置"""
        # 清空现有玩家
        self.texas_holdem.players = []

        # 添加真人玩家
        for player_name in self.human_players:
            player = Player(player_name, 1000, is_ai=False)
            self.texas_holdem.players.append(player)

        # 添加AI玩家
        ai_names = ["AI鲨鱼", "AI疯子", "AI机器人", "AI陷阱", "AI适应"]
        for i in range(self.ai_players):
            ai_name = ai_names[i % len(ai_names)] + str(i + 1) if i >= len(ai_names) else ai_names[i]
            player = Player(ai_name, 1000, is_ai=True)
            self.texas_holdem.players.append(player)

        # 更新AI风格映射
        self._update_ai_styles()

    def _update_ai_styles(self):
        """更新AI风格映射到新的玩家名"""
        # 保持原有的AI风格，但映射到新的AI玩家名
        ai_players = [p for p in self.texas_holdem.players if p.is_ai]
        original_styles = ["玩家1", "玩家2", "玩家3", "玩家4", "玩家5"]

        new_styles = {}
        for i, ai_player in enumerate(ai_players):
            if i < len(original_styles):
                old_key = original_styles[i]
                if old_key in self.texas_holdem.ai_styles:
                    new_styles[ai_player.name] = self.texas_holdem.ai_styles[old_key]

        # 更新ai_styles字典
        self.texas_holdem.ai_styles = new_styles

    async def remove_player(self, player_name: str):
        """从房间移除玩家"""
        if player_name in self.human_players:
            self.human_players.remove(player_name)
            print(f"玩家 {player_name} 离开房间")

            # 如果游戏进行中，需要处理游戏状态
            if self.room_state == RoomState.GAME_IN_PROGRESS:
                # 找到对应的玩家并设置为弃牌
                player = self._get_player_by_name(player_name)
                if player:
                    player.folded = True

                # 如果正在等待该玩家行动，继续游戏
                if self.waiting_for_player == player_name:
                    self.waiting_for_player = None
                    if self.action_timeout_task:
                        self.action_timeout_task.cancel()
                    await self._continue_betting_round()

            # 如果房间为空，重置状态
            if len(self.human_players) == 0:
                self.room_state = RoomState.WAITING_FOR_PLAYERS
                self.game_state = None
                print("房间为空，重置状态")

    async def start_game(self) -> Tuple[bool, str]:
        """开始游戏"""
        if self.room_state != RoomState.READY_TO_START:
            if len(self.human_players) == 0:
                return False, "房间没有玩家"
            elif len(self.human_players) < self.total_players - self.ai_players:
                return False, f"等待更多玩家加入 ({len(self.human_players)}/{self.total_players - self.ai_players})"
            else:
                return False, "游戏已经开始"

        # 切换房间状态
        self.room_state = RoomState.GAME_IN_PROGRESS

        print(f"游戏开始！真人玩家: {len(self.human_players)}, AI玩家: {self.ai_players}")

        # 初始化统计数据
        for player in self.texas_holdem.players:
            if player.name not in self.texas_holdem.player_stats:
                self.texas_holdem.player_stats[player.name] = {
                    "total_hands": 0,
                    "vpip": 0,
                    "pfr": 0,
                    "af": 0,
                    "wtsd": 0,
                    "w$sd": 0,
                    "fold_to_3bet": 0,
                    "fold_to_cbet": 0,
                    "check_raise": 0,
                    "donk_bet": 0,
                    "river_bluff_rate": 0,
                    "recent_aggression": []
                }

        # 开始新一轮
        await self.start_new_round()

        return True, "游戏开始"

    async def start_new_round(self):
        """开始新一轮游戏"""
        print("\n开始新一轮游戏")

        # 重置游戏状态
        self.texas_holdem.pot = 0
        self.texas_holdem.current_bet = 0
        self.texas_holdem.community_cards = []
        self.texas_holdem.board_texture = {
            "wetness": 0,
            "paired": False,
            "flush_possible": False,
            "straight_possible": False,
            "high_card_board": False
        }

        # 重置所有玩家状态
        for player in self.texas_holdem.players:
            player.reset_for_new_round()

        # 开始状态机
        await self.transition_to_state(GameState.DEALING_CARDS)

    async def handle_player_action(self, player_id: str, action: PlayerAction, amount: Optional[int] = None) -> Tuple[
        bool, str]:
        """处理玩家行动"""
        if self.room_state != RoomState.GAME_IN_PROGRESS:
            return False, "游戏未开始"

        if player_id not in self.human_players:
            return False, "玩家不在房间中"

        # 找到对应的玩家对象
        player = None
        for p in self.texas_holdem.players:
            if p.name == player_id:
                player = p
                break

        if not player:
            return False, "找不到玩家"

        # 检查是否轮到该玩家
        if self.waiting_for_player != player_id:
            return False, "不是你的回合"

        # 取消超时任务
        if self.action_timeout_task:
            self.action_timeout_task.cancel()
            self.action_timeout_task = None

        # 验证和执行行动
        try:
            await self._execute_player_action(player, action, amount)
            print(f"处理玩家 {player_id} 的行动: {action.value}" + (f" 金额: {amount}" if amount else ""))

            # 继续游戏流程
            await self._continue_betting_round()

            return True, "行动处理成功"

        except Exception as e:
            print(f"处理玩家行动错误: {e}")
            return False, f"行动处理失败: {str(e)}"

    async def _execute_player_action(self, player: Player, action: PlayerAction, amount: Optional[int]):
        """执行玩家行动"""
        to_call = self.texas_holdem.current_bet - player.current_bet

        if action == PlayerAction.CHECK:
            if to_call > 0:
                raise ValueError("不能过牌，需要跟注或弃牌")
            # 过牌不需要额外操作

        elif action == PlayerAction.CALL:
            if to_call <= 0:
                raise ValueError("没有需要跟注的金额")
            call_amount = min(to_call, player.chips)
            self.texas_holdem.make_bet(player, player.current_bet + call_amount)

        elif action == PlayerAction.BET:
            if to_call > 0:
                raise ValueError("已有下注，应该跟注或加注")
            if not amount or amount < self.texas_holdem.big_blind:
                raise ValueError(f"下注金额至少为 {self.texas_holdem.big_blind}")
            if amount > player.chips:
                raise ValueError("下注金额超过筹码数")
            self.texas_holdem.make_bet(player, amount)

        elif action == PlayerAction.RAISE:
            if to_call <= 0:
                raise ValueError("没有可加注的下注")
            if not amount:
                raise ValueError("加注必须指定金额")
            min_raise = self.texas_holdem.current_bet + self.texas_holdem.min_raise_amount
            if amount < min_raise:
                raise ValueError(f"加注金额至少为 {min_raise}")
            if amount > player.chips + player.current_bet:
                raise ValueError("加注金额超过筹码数")
            self.texas_holdem.make_bet(player, amount)

        elif action == PlayerAction.FOLD:
            player.folded = True

        elif action == PlayerAction.ALL_IN:
            all_in_amount = player.chips + player.current_bet
            self.texas_holdem.make_bet(player, all_in_amount)

        # 记录行动历史
        action_tuple = (action.value, amount) if amount else (action.value,)
        player.action_history.append((self.current_round_name, action_tuple))

        # 添加到已行动玩家集合
        self.players_acted.add(player)

    async def get_room_state(self) -> dict:
        """获取房间状态"""
        players_data = []

        # 添加真人玩家
        for player_name in self.human_players:
            player = self._get_player_by_name(player_name)
            if player:
                players_data.append({
                    "name": player.name,
                    "is_ai": False,
                    "chips": player.chips,
                    "status": "active" if not player.folded and player.chips > 0 else "inactive"
                })

        # 添加AI玩家
        for player in self.texas_holdem.players:
            if player.is_ai:
                players_data.append({
                    "name": player.name,
                    "is_ai": True,
                    "chips": player.chips,
                    "status": "active" if not player.folded and player.chips > 0 else "inactive"
                })

        return {
            "room_state": self.room_state.value,
            "players_count": len(self.human_players),
            "total_players": self.total_players,
            "ai_players": self.ai_players,
            "players": players_data
        }

    async def get_game_state(self, player_id: str) -> dict:
        """获取指定玩家的游戏状态"""
        if self.room_state != RoomState.GAME_IN_PROGRESS:
            return {
                "game_state": "not_started",
                "message": "游戏未开始"
            }

        player = self._get_player_by_name(player_id)
        if not player:
            return {
                "game_state": "error",
                "message": "玩家不存在"
            }

        # 序列化公共牌
        community_cards = []
        for card in self.texas_holdem.community_cards:
            community_cards.append({
                "rank": card.rank.symbol,
                "suit": card.suit.value
            })

        # 序列化手牌（只给真人玩家）
        your_hand = None
        if not player.is_ai and player.hand:
            your_hand = []
            for card in player.hand:
                your_hand.append({
                    "rank": card.rank.symbol,
                    "suit": card.suit.value
                })

        # 获取所有玩家信息
        players_info = []
        for p in self.texas_holdem.players:
            players_info.append({
                "name": p.name,
                "chips": p.chips,
                "current_bet": p.current_bet,
                "folded": p.folded,
                "all_in": p.all_in,
                "is_ai": p.is_ai,
                "is_current_player": (self.waiting_for_player == p.name)
            })

        # 计算需要跟注的金额
        to_call = max(0, self.texas_holdem.current_bet - player.current_bet)

        # 获取有效行动
        valid_actions = self._get_valid_actions_for_player(player)

        # 计算最小加注金额
        min_raise = None
        if "raise" in valid_actions:
            min_raise = self.texas_holdem.current_bet + self.texas_holdem.min_raise_amount

        return {
            "game_state": self.game_state.value if self.game_state else "unknown",
            "round_name": self.current_round_name,
            "community_cards": community_cards,
            "pot": self.texas_holdem.pot,
            "current_bet": self.texas_holdem.current_bet,
            "players": players_info,
            "your_hand": your_hand,
            "your_turn": (self.waiting_for_player == player_id),
            "valid_actions": valid_actions,
            "to_call": to_call,
            "min_raise": min_raise
        }

    def _get_player_by_name(self, name: str) -> Optional[Player]:
        """根据名字获取玩家对象"""
        for player in self.texas_holdem.players:
            if player.name == name:
                return player
        return None

    def _get_valid_actions_for_player(self, player: Player) -> List[str]:
        """获取玩家可执行的有效行动"""
        if player.folded or player.all_in:
            return []

        if self.waiting_for_player != player.name:
            return []

        valid_actions = []
        to_call = self.texas_holdem.current_bet - player.current_bet

        if to_call == 0:
            # 可以过牌或下注
            valid_actions.extend(["check", "bet"])
        else:
            # 需要跟注、加注或弃牌
            valid_actions.extend(["call", "raise"])

        # 总是可以弃牌（除非已经过牌且无需跟注）
        if to_call > 0:
            valid_actions.append("fold")

        # 总是可以全押（如果有筹码）
        if player.chips > 0:
            valid_actions.append("all_in")

        return valid_actions

    # ==================== 状态机相关方法 ====================

    async def transition_to_state(self, new_state: GameState):
        """状态转换"""
        old_state = self.game_state
        self.game_state = new_state
        print(f"游戏状态转换: {old_state} -> {new_state}")

        # 执行状态对应的游戏逻辑
        await self._execute_state_action(new_state)

        # 广播状态更新
        if self.websocket_handler:
            await self.websocket_handler.broadcast_game_state()

    async def _execute_state_action(self, state: GameState):
        """执行状态对应的动作"""
        if state == GameState.DEALING_CARDS:
            await self._deal_cards()
        elif state == GameState.POSTING_BLINDS:
            await self._post_blinds()
        elif state == GameState.PREFLOP_BETTING:
            await self._start_betting_round("翻牌前")
        elif state == GameState.DEALING_FLOP:
            await self._deal_flop()
        elif state == GameState.FLOP_BETTING:
            await self._start_betting_round("翻牌")
        elif state == GameState.DEALING_TURN:
            await self._deal_turn()
        elif state == GameState.TURN_BETTING:
            await self._start_betting_round("转牌")
        elif state == GameState.DEALING_RIVER:
            await self._deal_river()
        elif state == GameState.RIVER_BETTING:
            await self._start_betting_round("河牌")
        elif state == GameState.SHOWDOWN:
            await self._showdown()
        elif state == GameState.ROUND_END:
            await self._round_end()

    # ==================== 游戏逻辑方法 ====================

    async def _deal_cards(self):
        """发牌"""
        print("发牌中...")
        self.texas_holdem.create_deck()
        self.texas_holdem.deal_cards()
        await asyncio.sleep(0.5)
        await self.transition_to_state(GameState.POSTING_BLINDS)

    async def _post_blinds(self):
        """下盲注"""
        print("下盲注...")
        self.texas_holdem.post_blinds()
        await asyncio.sleep(0.5)
        await self.transition_to_state(GameState.PREFLOP_BETTING)

    async def _start_betting_round(self, round_name: str):
        """开始下注轮"""
        print(f"开始{round_name}下注轮")
        self.current_round_name = round_name
        self.betting_state = BettingState.WAITING_FOR_ACTION
        self.players_acted.clear()

        # 重置最小加注额
        self.texas_holdem.min_raise_amount = self.texas_holdem.big_blind

        # 确定起始位置
        if round_name == "翻牌前":
            # 翻牌前从大盲注后一位开始
            start_position = (self.texas_holdem.dealer_position + 3) % len(self.texas_holdem.players)
        else:
            # 其他轮从小盲注开始
            start_position = (self.texas_holdem.dealer_position + 1) % len(self.texas_holdem.players)
            while (start_position < len(self.texas_holdem.players) and
                   (self.texas_holdem.players[start_position].folded or
                    self.texas_holdem.players[start_position].chips == 0)):
                start_position = (start_position + 1) % len(self.texas_holdem.players)

        self.current_player_index = start_position

        # 开始处理第一个玩家
        await self._process_current_player()

    async def _process_current_player(self):
        """处理当前玩家回合"""
        # 找到下一个需要行动的玩家
        attempts = 0
        while attempts < len(self.texas_holdem.players):
            current_player = self.texas_holdem.players[self.current_player_index]

            # 跳过已弃牌、全押或没筹码的玩家
            if current_player.folded or current_player.all_in or current_player.chips == 0:
                await self._next_player()
                attempts += 1
                continue

            # 检查是否需要行动
            if (current_player.current_bet < self.texas_holdem.current_bet or
                    current_player not in self.players_acted):

                if current_player.is_ai:
                    # AI玩家立即处理
                    await self._process_ai_action(current_player)
                else:
                    # 真人玩家等待输入
                    await self._wait_for_human_action(current_player)
                return
            else:
                # 玩家已经行动过且下注相同，跳过
                await self._next_player()
                attempts += 1

        # 所有玩家都行动过，结束下注轮
        await self._end_betting_round()

    async def _process_ai_action(self, player: Player):
        """处理AI行动"""
        print(f"AI {player.name} 思考中...")

        # 通知前端AI正在思考
        if self.websocket_handler:
            await self.websocket_handler.broadcast_message(
                "ai_action",
                {
                    "player": player.name,
                    "status": "thinking"
                }
            )

        await asyncio.sleep(0.8)  # 模拟思考时间

        # 调用texas_holdem的AI逻辑
        last_aggressor = self._get_last_aggressor()
        action = self.texas_holdem.enhanced_ai_action(player, self.current_round_name, last_aggressor)

        if action:
            # 记录行动历史
            player.action_history.append((self.current_round_name, action))
            self.players_acted.add(player)

            # 更新最小加注额
            if action[0] in ['raise', 'bet'] and len(action) > 1:
                if action[0] == 'raise':
                    self.texas_holdem.min_raise_amount = action[1] - self.texas_holdem.current_bet

            # 通知前端AI的行动
            if self.websocket_handler:
                action_data = {
                    "player": player.name,
                    "action": action[0],
                    "amount": action[1] if len(action) > 1 else None,
                    "action_text": self._get_action_description(action)
                }
                await self.websocket_handler.broadcast_message("ai_action", action_data)

                # 等待一下让玩家看到AI的行动
                await asyncio.sleep(0.5)

        # 继续下一个玩家
        await self._next_player()
        await self._process_current_player()

    def _get_action_description(self, action):
        """获取行动描述"""
        action_type = action[0]
        amount = action[1] if len(action) > 1 else None

        descriptions = {
            'check': '过牌',
            'call': '跟注',
            'fold': '弃牌',
            'bet': f'下注 {amount}' if amount else '下注',
            'raise': f'加注到 {amount}' if amount else '加注',
            'all_in': '全押'
        }

        return descriptions.get(action_type, action_type)

    async def _wait_for_human_action(self, player: Player):
        """等待真人行动"""
        self.waiting_for_player = player.name
        print(f"等待玩家 {player.name} 行动...")

        # 发送行动请求
        if self.websocket_handler:
            action_data = {
                "player_name": player.name,
                "timeout": 30,
                "valid_actions": self._get_valid_actions_for_player(player),
                "to_call": max(0, self.texas_holdem.current_bet - player.current_bet),
                "min_raise": self.texas_holdem.current_bet + self.texas_holdem.min_raise_amount if self.texas_holdem.current_bet > 0 else self.texas_holdem.big_blind,
                "pot": self.texas_holdem.pot,
                "current_bet": self.texas_holdem.current_bet
            }
            await self.websocket_handler.send_action_request(player.name, action_data)

        # 启动超时任务
        self.action_timeout_task = asyncio.create_task(self._action_timeout(player))

    async def _action_timeout(self, player: Player):
        """玩家行动超时处理"""
        try:
            await asyncio.sleep(30)  # 30秒超时
            print(f"玩家 {player.name} 行动超时，自动弃牌")

            # 超时自动弃牌
            player.folded = True
            player.action_history.append((self.current_round_name, ('fold',)))
            self.players_acted.add(player)

            self.waiting_for_player = None

            # 继续游戏
            await self._continue_betting_round()

        except asyncio.CancelledError:
            # 任务被取消（玩家及时行动了）
            pass

    async def _continue_betting_round(self):
        """继续下注轮"""
        await self._next_player()
        await self._process_current_player()

    async def _next_player(self):
        """切换到下一个玩家"""
        self.current_player_index = (self.current_player_index + 1) % len(self.texas_holdem.players)

    async def _end_betting_round(self):
        """结束下注轮"""
        print(f"{self.current_round_name}下注轮结束")
        self.betting_state = BettingState.BETTING_COMPLETE
        self.waiting_for_player = None

        # 重置当前轮的下注
        for player in self.texas_holdem.players:
            player.current_bet = 0
        self.texas_holdem.current_bet = 0

        # 检查是否只剩一个玩家
        active_players = [p for p in self.texas_holdem.players if not p.folded]
        if len(active_players) <= 1:
            await self.transition_to_state(GameState.SHOWDOWN)
            return

        # 根据当前轮次转换到下一状态
        if self.current_round_name == "翻牌前":
            await self.transition_to_state(GameState.DEALING_FLOP)
        elif self.current_round_name == "翻牌":
            await self.transition_to_state(GameState.DEALING_TURN)
        elif self.current_round_name == "转牌":
            await self.transition_to_state(GameState.DEALING_RIVER)
        elif self.current_round_name == "河牌":
            await self.transition_to_state(GameState.SHOWDOWN)

    def _get_last_aggressor(self) -> Optional[Player]:
        """获取最后一个加注/下注的玩家"""
        for player in reversed(self.texas_holdem.players):
            if player.action_history:
                last_action = player.action_history[-1]
                if len(last_action) > 1 and last_action[1][0] in ['bet', 'raise']:
                    return player
        return None

    async def _deal_flop(self):
        """发翻牌"""
        print("发翻牌...")
        self.texas_holdem.deal_community_cards(3)
        print(f"翻牌: {self.texas_holdem.community_cards}")
        await asyncio.sleep(1)
        await self.transition_to_state(GameState.FLOP_BETTING)

    async def _deal_turn(self):
        """发转牌"""
        print("发转牌...")
        self.texas_holdem.deal_community_cards(1)
        print(f"转牌: {self.texas_holdem.community_cards}")
        await asyncio.sleep(1)
        await self.transition_to_state(GameState.TURN_BETTING)

    async def _deal_river(self):
        """发河牌"""
        print("发河牌...")
        self.texas_holdem.deal_community_cards(1)
        print(f"河牌: {self.texas_holdem.community_cards}")
        await asyncio.sleep(1)
        await self.transition_to_state(GameState.RIVER_BETTING)

    async def _showdown(self):
        """摊牌"""
        print("摊牌中...")

        # 获取摊牌前的玩家状态
        active_players = [p for p in self.texas_holdem.players if not p.folded]

        # 调用德州扑克引擎的摊牌逻辑
        self.texas_holdem.showdown()

        # 收集摊牌结果信息
        showdown_data = await self._collect_showdown_results(active_players)

        # 发送摊牌结果给前端
        if self.websocket_handler:
            await self.websocket_handler.broadcast_message(
                "showdown_result",
                showdown_data
            )

        await asyncio.sleep(3)  # 给玩家时间查看结果
        await self.transition_to_state(GameState.ROUND_END)

    async def _collect_showdown_results(self, active_players):
        """收集摊牌结果信息"""
        results = []

        if len(active_players) == 1:
            # 只有一个玩家，直接获胜
            winner = active_players[0]
            results.append({
                "type": "single_winner",
                "winner": winner.name,
                "amount": self.texas_holdem.pot,
                "reason": "所有其他玩家弃牌"
            })
        else:
            # 多个玩家摊牌
            player_hands = []
            for player in active_players:
                all_cards = player.hand + self.texas_holdem.community_cards
                hand_rank, hand_values = self.texas_holdem.evaluate_hand(all_cards)

                # 序列化手牌信息
                hand_cards = []
                if player.hand:
                    for card in player.hand:
                        hand_cards.append({
                            "rank": card.rank.symbol,
                            "suit": card.suit.value
                        })

                player_hands.append({
                    "player": player.name,
                    "hand": hand_cards,
                    "hand_rank": hand_rank.name,
                    "hand_description": self._get_hand_description(hand_rank, hand_values)
                })

            # 按牌型排序找出获胜者
            # 这里简化处理，实际上德州扑克引擎已经处理了获胜逻辑
            # 我们可以通过比较筹码变化来确定获胜者
            results.append({
                "type": "showdown",
                "players": player_hands,
                "pot": self.texas_holdem.pot
            })

        return {
            "results": results,
            "pot": self.texas_holdem.pot,
            "community_cards": [
                {"rank": card.rank.symbol, "suit": card.suit.value}
                for card in self.texas_holdem.community_cards
            ]
        }

    def _get_hand_description(self, hand_rank, hand_values):
        """获取牌型描述"""
        hand_names = {
            "HIGH_CARD": "高牌",
            "PAIR": "一对",
            "TWO_PAIR": "两对",
            "THREE_OF_A_KIND": "三条",
            "STRAIGHT": "顺子",
            "FLUSH": "同花",
            "FULL_HOUSE": "葫芦",
            "FOUR_OF_A_KIND": "四条",
            "STRAIGHT_FLUSH": "同花顺",
            "ROYAL_FLUSH": "皇家同花顺"
        }
        return hand_names.get(hand_rank.name, hand_rank.name)

    async def _round_end(self):
        """回合结束"""
        print("回合结束")

        # 发送回合结束消息
        if self.websocket_handler:
            await self.websocket_handler.broadcast_message(
                "round_end",
                {
                    "message": "回合结束，准备下一轮...",
                    "next_round_in": 5
                }
            )

        # 移动庄家位置
        self.texas_holdem.dealer_position = (self.texas_holdem.dealer_position + 1) % len(self.texas_holdem.players)
        while (self.texas_holdem.dealer_position < len(self.texas_holdem.players) and
               self.texas_holdem.players[self.texas_holdem.dealer_position].chips <= 0):
            self.texas_holdem.dealer_position = (self.texas_holdem.dealer_position + 1) % len(self.texas_holdem.players)

        await asyncio.sleep(5)  # 增加等待时间到5秒

        # 检查游戏是否结束
        active_players = [p for p in self.texas_holdem.players if p.chips > 0]
        if len(active_players) <= 1:
            print("游戏结束!")
            self.room_state = RoomState.GAME_FINISHED

            if self.websocket_handler:
                await self.websocket_handler.broadcast_message(
                    "game_end",
                    {
                        "winner": active_players[0].name if active_players else "无人获胜",
                        "final_chips": {p.name: p.chips for p in self.texas_holdem.players}
                    }
                )
            return

        # 检查是否还有真人玩家
        human_players_active = [p for p in self.texas_holdem.players if not p.is_ai and p.chips > 0]
        if len(human_players_active) == 0:
            print("所有真人玩家已淘汰!")
            self.room_state = RoomState.GAME_FINISHED

            if self.websocket_handler:
                await self.websocket_handler.broadcast_message(
                    "game_end",
                    {
                        "message": "所有真人玩家已淘汰",
                        "final_chips": {p.name: p.chips for p in self.texas_holdem.players}
                    }
                )
            return

        # 开始新一轮
        await self.start_new_round()

    def set_websocket_handler(self, handler):
        """设置WebSocket处理器回调"""
        self.websocket_handler = handler